package com.ynqxg.router.view

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.RectF
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.View
import androidx.core.graphics.drawable.toBitmapOrNull
import com.ynqxg.router.R


class SmartImageView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val imagePaint = Paint()
    private val imageDrawable: Drawable?
    private var radius = 0f

    init {
        // 读取xml获得的参数
        val attributes = context.obtainStyledAttributes(attrs, R.styleable.SmartImageView)
        imageDrawable = attributes.getDrawable(R.styleable.SmartImageView_android_src)
        radius = attributes.getDimension(R.styleable.SmartImageView_radius, 0f)
        attributes.recycle()
        // 初始化画笔属性
        imagePaint.isAntiAlias = true
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        // 测量宽度
        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        var widthSize = MeasureSpec.getSize(widthMeasureSpec)
        if (widthMode == MeasureSpec.AT_MOST) {
            widthSize = (imageDrawable?.intrinsicWidth ?: 0)
        }
        // 测量高度
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        var heightSize = MeasureSpec.getSize(heightMeasureSpec)
        if (heightMode == MeasureSpec.AT_MOST) {
            // 高度自适应时按照宽度缩放比例计算
            heightSize = widthSize.div(imageDrawable?.intrinsicWidth ?: 0)
                .times(imageDrawable?.intrinsicHeight ?: 1)
        }
        setMeasuredDimension(widthSize, heightSize)
    }

    override fun draw(canvas: Canvas?) {
        super.draw(canvas)
        canvas?.also { c ->
            // 计算绘制的启动xy坐标和范围的宽高
            val x = paddingStart.toFloat()
            val y = paddingTop.toFloat()
            val safeWidth = measuredWidth.minus(paddingStart).minus(paddingEnd)
            val safeHeight = measuredHeight.minus(paddingTop).minus(paddingBottom)
            // 获得圆角处理后的图片对象
            createFramedPhoto(safeWidth, safeHeight)?.also {
                // 如果图片宽度和View宽度不一致，则缩放为对应宽高
                var bitmap = it
                if (safeWidth != imageDrawable?.intrinsicWidth) {
                    bitmap = Bitmap.createScaledBitmap(it, safeWidth, safeHeight, false)
                }
                c.drawBitmap(bitmap, x, y, imagePaint)
            }
        }
    }

    /**
     *
     * @param x 图像的宽度
     * @param y 图像的高度
     * @return 圆角图片
     */
    private fun createFramedPhoto(x: Int, y: Int): Bitmap? {
        if (radius <= 0) {
            return imageDrawable?.toBitmapOrNull()
        }
        // 新建一个新的输出图片
        val newBitmap = Bitmap.createBitmap(x, y, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(newBitmap)
        // 新建一个矩形
        val outerRect = RectF(0f, 0f, x.toFloat(), y.toFloat())

        // 产生一个红色的圆角矩形
        val paint = Paint(Paint.ANTI_ALIAS_FLAG)
        canvas.drawRoundRect(outerRect, radius, radius, paint)

        // 将源图片绘制到这个圆角矩形上
        paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
        imageDrawable?.setBounds(0, 0, x, y)
        canvas.saveLayer(outerRect, paint)
        imageDrawable?.draw(canvas)
        canvas.restore()
        return newBitmap
    }


}